package fun.util.daohelper;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.io.Serializable;

/**
 * Created by IntelliJ IDEA.
 * User: bin
 * Date: Jan 9, 2006
 * Time: 10:34:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class PrimaryKeyUtil {

    private static final char SEPARATOR = ':';

    public static String serializePK( PrimaryKey key ) {
        return key.getClass().getName() + ":" + key.getValue();
    }

    public static PrimaryKey deserializePK( String serializedPK ) {
        int separatorIndex = serializedPK.lastIndexOf( SEPARATOR );
        String className = serializedPK.substring( 0, separatorIndex );
        Long value = Long.parseLong( serializedPK.substring( separatorIndex + 1 ) );

        try {
            Class pkType = Class.forName( className );
            return createPK( pkType, value );
        } catch ( ClassNotFoundException e) {
            throw new RuntimeException( "invalid serializedPK class: " + className + " for: " + serializedPK );
        }
    }

    public static <T extends PrimaryKey> T createPK( Class<? extends T> typeClass, Serializable value ) {
        try {
            Constructor[] constructors = typeClass.getDeclaredConstructors( );
            Constructor constructor = constructors[0];
            constructor.setAccessible( true );
            return (T)constructor.newInstance( value );
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        }

    }
}
